import fs from 'fs'
import conf from '../config/conf.js'
/**
 * 读取文件
 * @param path filefullpath
 * @returns file content
 */
export function readFile (path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, conf['encode'], (err, data) => {
      if (err) {
        console.error(`readFile failed, caused by ${JSON.stringify(err)}`);
        reject(false);
      } else {
        resolve(JSON.parse(data));
        return;
      }
    });
  }).catch(error => {
    console.error(`error happened when readFile: ${error.message}`);
  });
}

/**
 * 更新文件
 * @param   res  to update content
 * @returns update operation result
 */
export function updateResFile (path, res) {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, JSON.stringify(res), conf['encode'], (err) => {
      if (err) {
        console.error(`error happened when updateResFile inner: ${err.message}`);
        reject({
          data: false,
          message: err.message
        });
        return;
      } else {
        resolve({
          data: true,
          message: '成功！'
        });
        return;
      }
    });
  }).catch(error => {
    console.error(`error happened when updateResFile: ${error.message}`);
    return {
      data: false,
      message: error.message
    };
  });
}

/**
 * 上传单个文件
 * @param path filefullpath
 * @returns file content
 */
export function uploadSingleFile (file, targetPath) {
  return new Promise((resolve, reject) => {
    const desFile = `${targetPath}${file.originalname}`
    
    fs.readFile(file.path, (err, data) => {
      fs.writeFile(desFile, data, (err) => {
        if (err) {
          console.log( err );
          reject({
            status: false
          });
          return;
        } else {
          const response = {
            message:'File uploaded successfully',
            filename: file.originalname
          };
          console.log( response );
          resolve({
            status: true,
            path: desFile.split('/').slice(1).join('/'),
            fileName: file.originalname,
            fileDir: targetPath
          });
          return;
        }
      });
    });
  }).catch(error => {
    console.error(`error happened when uploadFile: ${error.message}`);
    return false;
  })
}

/**
 * 上传多个文件
 * @param path filefullpath
 * @returns file content
 */
export function uploadFiles (files) {
  const targetPath = `public/files/${Date.now()}/`
  const isDirExist = fs.existsSync(targetPath)
  !isDirExist && fs.mkdirSync(targetPath)
  
  return Promise.all(files.map(file => uploadSingleFile(file, targetPath)))
    .finally(() => {
      delDir({path: conf.uploadTmpDir, isDeleteSelf: false})
    })
}

/**
 * 删除指定文件夹下的所有文件
 * @param path filefullpath
 * @returns file content
 */
export function delDir ({path, isDeleteSelf}) {
  let files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach(file => {
      let curPath = `${path}/${file}`
      if (fs.statSync(curPath).isDirectory()) {
        delDir(curPath); //递归删除文件夹
      } else {
        fs.unlinkSync(curPath); //删除文件
      }
    });
    // 删除文件夹自身
    isDeleteSelf && fs.rmdirSync(path)
  }
}

